import routes from "./routerMaps";
import axios from "axios";
import { deepClone } from "@/utils/utils";

let localRouteFlatten = getFlattenRouten(routes);
export default (router) => {
  axios.get("http://127.0.0.1:3003/routes").then((res) => {
    let or = res.data;
    let relRoutes = getRelRoutes(or);
    relRoutes.forEach((item) => {
      router.addRoute(item);
    });
  });
};

function getRelRoutes(routes) {
  let routeMap = [];
  routes.forEach((route) => {
    let matchRoute = localRouteFlatten.find((item) => item.name === route.name);
    if (!matchRoute) return;
    if (route.children) {
      matchRoute.children = getRelRoutes(route.children);
    }
    routeMap.push(matchRoute);
  });
  return routeMap;
}

function getFlattenRouten(routes, parantName) {
  let rs = [];
  routes.forEach((item) => {
    if (parantName) {
      item.parantName = parantName;
    }
    rs.push(item);
    if (item.children) {
      rs = [...rs, ...getFlattenRouten(item.children, item.name)];
    }
  });
  return rs;
}
